#!/usr/bin/python3
# -*- coding: utf-8 -*-

import smtplib, sys, re, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart, MIMEBase
from email.utils import formataddr
from email import encoders

# SMTP配置
SENDER_USER_NAME = 'qms@kuaidihelp.com'
# SENDER_PASS_WORD = 'zentao@kuaibao2015.com'
SENDER_PASS_WORD = 'TcCQayJz7PTUPnbs'
SMTP_SERVER_URL = 'smtp.exmail.qq.com'
SMTP_SERVER_PORT = 465
HTLP_TEXT = '''
     send_mail 收件人邮件地址[,收件人地址 ,...] 内容 [标题] [发送人名称] [附件地址[,附件地址 ,...]]
     样例:
        send_mail ab@kuaidihelp.com "发送测试"
        send_mail ab@kuaidihelp.com "发送测试" "标题"
        send_mail ab@kuaidihelp.com,cd@qq.com, ex@qq.com "发送测试" "标题"
        send_mail ab@kuaidihelp.com,cd@qq.com, ex@qq.com "发送测试" "标题" "通知"
        send_mail ab@kuaidihelp.com,cd@qq.com, ex@qq.com "发送测试" "标题" "通知" "附件列表"
     收件人地址必须是有效的邮箱地址
    '''


def send_mail(recievers, msg, title='', mail_from='', file_list=''):
    try:
        if recievers and re.match(r'([^@]+@[^@]+\.[^@]+)+', recievers) and msg:
            msg_body = MIMEText(msg, 'plain', 'utf-8')
            msg_obj = MIMEMultipart()
            msg_obj['Subject'] = title if title else '无标题'
            msg_obj['From'] = formataddr([mail_from, SENDER_USER_NAME]) if mail_from else SENDER_USER_NAME
            msg_obj['To'] = recievers
            msg_obj.attach(msg_body)
            if file_list:
                files = [file_list.strip()]
                try:
                    if file_list.index(','):
                        files = [file.strip() for file in file_list.split(',') if file.strip()]
                except:
                    pass
                for file in files:
                    if not os.path.isfile(file):
                        continue
                    ctype = 'application/octet-stream'
                    maintype, subtype = ctype.split('/', 1)
                    with open(file, 'rb') as fp:
                        msg_attachment = MIMEBase(maintype, subtype)
                        msg_attachment.set_payload(fp.read())
                    encoders.encode_base64(msg_attachment)
                    msg_attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
                    msg_obj.attach(msg_attachment)
            try:
                server = smtplib.SMTP_SSL(SMTP_SERVER_URL, SMTP_SERVER_PORT)
            except smtplib.SMTPConnectError:
                print('连接错误')
                return
            try:
                if recievers.index(','):
                    recievers = [mail.strip() for mail in recievers.split(',') if mail.strip()]
            except:
                pass
            try:
                server.login(SENDER_USER_NAME, SENDER_PASS_WORD)
            except smtplib.SMTPAuthenticationError:
                print('密码或账号错误')
                return
            server.sendmail(SENDER_USER_NAME, recievers, msg_obj.as_string())
            server.close()
            print('发送成功')
        else:
            print('参数错误:收件人和收件内容不能为空' + HTLP_TEXT)
    except:
        print('error happened')

if len(sys.argv) > 2:
    send_mail(*sys.argv[1:6])
else:
    print(sys.argv[1:])
    print(HTLP_TEXT)
